package com.fingard.dsp.bank.directbank.hxb01;


import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.InterBankPayChannel;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

public class HXB01SinglePay extends HXB01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail=null;
        if("190802B".equals(p_req1908.reqHeader.commandCode)){
        	//单笔转账（xhj8016），提交：xhj8016，查询：xhj5001
        	tmpRetDetail = d_190802_xhj8016(p_req1908);
        }
        else if("1".equals(getBankConfig().getValueAsString("samePrivateFlag")) && "1".equals(p_req1908.singleDetail.isPrivate) && "1".equals(p_req1908.singleDetail.sameBnk)){//对私
            tmpRetDetail = d_190802_Private(p_req1908);
        }else {//对公
            tmpRetDetail = d_190802(p_req1908);
        }
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    /**
     * 华夏银行单笔支付
     *
     * @param p_req1908
     * @return
     * @throws Exception
     */
    private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        //日期格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String sendInfo = "{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#{9}#{10}#{11}#{12}#{13}#{14}#@@@@";
        String tran_code = "xhj0016";//0.交易代码
        String entryDate = df.format(new Date()) + "";//1.录入日期
        String transType = (p_req1908.singleDetail.sameBnk.equals("1")) ? ("1") : ("2");//原.net系统此处判断是否需要走网银转账，此处暂不处理
        String FlowNo = "";//企业端流水号
        if (p_req1908.singleDetail.askNumber.length() <= 20) {
            FlowNo = p_req1908.singleDetail.askNumber;
        } else {
            retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到客户端发送的付款账号超过银行规定的最大位数20";
        }
        String custID = "9999999999";//企业经办人固定值
        String PayerAcct = "";//付款账号
        if (PayerAcct.length() <= 22) {
            PayerAcct = p_req1908.singleDetail.payAct;
        } else {
            retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到客户端发送的付款账号超过银行规定的最大位数22";
        }
        String Amount = p_req1908.singleDetail.payAmount;//发生额
        String payeeAcctNo = p_req1908.singleDetail.recAct;//收款账号
        String payeeName = p_req1908.singleDetail.recName;//收款人名称
        String payeeBankName = p_req1908.singleDetail.recBankName;//收款行名
        String payeeBankAddr = "";//收款行地址 - 空
        String clringno = p_req1908.singleDetail.cnapsCode;//收款行联行号
        String abstractStr = p_req1908.singleDetail.purpose;//摘要
        String Note1 = p_req1908.singleDetail.abstractATS;//备用域
        String Note2 = p_req1908.singleDetail.abstractATS;//备用2
        sendInfo = MessageFormat.format(sendInfo, tran_code, entryDate, transType, FlowNo, custID, PayerAcct, Amount, payeeAcctNo, payeeName,
                payeeBankName, payeeBankAddr, clringno, abstractStr, Note1, Note2);

        System.out.println("发送银行报文：" + sendInfo);//打印返回报文
        String[] tmpStrRet = sendToBank(sendInfo);//发送银行

        if (tmpStrRet[0].length() == 0) {
            String[] resultArr = tmpStrRet[1].split("#");
            String tmpRetCode = resultArr[0];
            if (null != tmpRetCode) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = tmpRetCode;
                retDetail.payInfoCode = tmpRetCode;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = "银行返回的数据格式不符合预期";
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }
    
    /**
     * 单笔转账（xhj8016）
     *
     * @param p_req1908
     * @return
     * @throws Exception
     */
    private RetAtsSglDetail d_190802_xhj8016(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        //日期格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String sendInfo = "{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#{9}#{10}#{11}#{12}#{13}#{14}#{15}#{16}#@@@@";
        String tran_code = "xhj8016";//0.交易代码
        String flowNo = p_req1908.singleDetail.askNumber;//企业端流水号
        String entryDate = Format.Date8Format.format(p_req1908.singleDetail.getPayDateOnly());
        String operNo = bankFront.operator;//企业经办人
        String payAcctNo = p_req1908.singleDetail.payAct;//付款账号
        String payAcctBooks = "";//付款方账簿号
        String amount = p_req1908.singleDetail.payAmount;//金额
        String payeetype = "";//收款方类别 0-企业   1-个人
        if("1".equals(p_req1908.singleDetail.isPrivate)){
        	payeetype = "1";
        }else{
        	payeetype = "0";
        }
        String transtype = "";//转账类型 0-大额付系统，1-小额支付   系统：暂未上线，2-同城票交，3-跨行清算，4-行内
        String payeeAcctNo = p_req1908.singleDetail.recAct;//收款人账号
        String payeeAcctName = p_req1908.singleDetail.recName;//收款人户名
        String payeeBankNo = p_req1908.singleDetail.getCnapsCodeNot999();//收款方开户行联行行号
        String payeeBankName = p_req1908.singleDetail.getOppBankLocation();//收款方开户行行名
        if("1".equals(p_req1908.singleDetail.sameBnk)){
        	transtype = "4";
        }else{
        	
        	InterBankPayChannel bnkPayChan = getInterBankPayChannel(p_req1908.singleDetail);
        	if(bnkPayChan.isPiaoJiao){
        		transtype = "2";//2-同城票交
        	}else if(bnkPayChan.isEBank){
        		transtype = "3";//3-跨行清算
        		payeeBankNo = bnkPayChan.eBankCode;
        		payeeBankName = bnkPayChan.eBankName;
        	}else if(bnkPayChan.isLargeChannel){
        		transtype = "0";//0-大额付系统
        	}else{
        		transtype = "1";//1-小额支付
        	}
        }

        HashMap<String,String> trgMap = new HashMap<String,String>();
        trgMap.put("summary", p_req1908.singleDetail.purpose);//附言 140
        trgMap.put("note1", p_req1908.singleDetail.askNumber);//note1 备用域1
        trgMap.put("note2", p_req1908.singleDetail.abstractATS);//note2 备用域2
        trgMap.put("note3", p_req1908.singleDetail.paymentCode);//note3 备用域3
        this.nodeAnalysis(p_req1908.singleDetail.srcXElement, trgMap, this.getCharset());
        String summary = trgMap.get("summary");
        String note1 = trgMap.get("note1");
        String note2 = trgMap.get("note2");
        String note3 = trgMap.get("note3");
        summary = StringHelper.subStringByByte(summary, getCharset(), 140);
        sendInfo = MessageFormat.format(sendInfo, tran_code, flowNo, entryDate, operNo, payAcctNo, payAcctBooks, amount, payeetype, transtype, payeeAcctNo, payeeAcctName, payeeBankNo, payeeBankName, summary, note1, note2, note3);
        String[] tmpStrRet = sendToBank(sendInfo);//发送银行
        if (tmpStrRet[0].length() == 0) {
            String[] resultArr = tmpStrRet[1].split("#");
            String tmpRetCode = resultArr[0];
            if(resultArr.length > 2){
                String bkEntFlowNo = resultArr[1];
                if(p_req1908.singleDetail.askNumber.equals(bkEntFlowNo)){
                	retDetail.respCode = "0";
                    retDetail.respInfo = tmpStrRet[1];
                    retDetail.reqSeqID = bkEntFlowNo;
                    retDetail.transState = tmpRetCode;
                    retDetail.payInfoCode = tmpRetCode;
                }else{
                	retDetail.respCode = "-1";
                    retDetail.respInfo = "银行返回entFlowNo值"+bkEntFlowNo+"与请求值"+p_req1908.singleDetail.askNumber+"不一致";
                }
            }else if(resultArr.length == 2 && "@@@@".equals(resultArr[1].trim())){
            	retDetail.respInfo = convertRespToBank(tmpRetCode);//获取银行返回信息
            	retDetail.respCode = "0";
            	retDetail.transState = tmpRetCode;
                retDetail.payInfoCode = tmpRetCode;
                retDetail.reqSeqID = flowNo;
            }else {
                retDetail.respCode = "-1";
                retDetail.respInfo = "银行返回的内容“"+tmpStrRet[1]+"”格式不符合预期";
            }
        }else if(FailCode.E9999.equals(tmpStrRet[0])){
        	retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = FailCode.E9999;
            retDetail.payInfoCode = FailCode.E9999;
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }
    

    /**
     * 华夏银行单笔支付-对私
     *
     * @param p_req1908
     * @return
     * @throws Exception
     */
    private RetAtsSglDetail d_190802_Private(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        //日期格式化
        //SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String sendInfo = "{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#@@@@";
        String tran_code = "xhj3005";//0.交易代码
        String acctName=p_req1908.singleDetail.payName;//客户名称
        String payerAcct = "";//付款账号
        if (payerAcct.length() <= 22) {
            payerAcct = p_req1908.singleDetail.payAct;
        } else {
            retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到客户端发送的付款账号超过银行规定的最大位数22";
        }
        String cardNo=p_req1908.singleDetail.recAct;//卡号
        String accountName=p_req1908.singleDetail.recName;//户名
        String amount = p_req1908.singleDetail.payAmount;//金额
        String note = p_req1908.singleDetail.purpose;//摘要
        String telno=p_req1908.singleDetail.cellPhone;//手机号
        String flowNo = "";//企业端流水号
        if (p_req1908.singleDetail.askNumber.length() <= 20) {
            flowNo = p_req1908.singleDetail.askNumber;
        } else {
            retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到客户端发送的付款账号超过银行规定的最大位数20";
        }
        sendInfo = MessageFormat.format(sendInfo, tran_code, acctName, payerAcct, cardNo, accountName, amount, note, telno, flowNo);
        String[] tmpStrRet = sendToBank(sendInfo);//发送银行
        if (tmpStrRet[0].length() == 0) {
            String[] resultArr = tmpStrRet[1].split("#");
            String tmpRetCode = resultArr[0];
            if (null != tmpRetCode) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = tmpRetCode;
                retDetail.payInfoCode = tmpRetCode;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = "银行返回的数据格式不符合预期";
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    /**
     * 华夏银行单笔交易查询
     *
     * @return
     * @throws Exception
     */
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
    	
    	if("190802B".equals(p_req1944.reqHeader.commandCode)){
        	//单笔转账（xhj8016），提交：xhj8016，查询：xhj5001
        	return d_1944_xhj5001(p_req1944);
        }else{
        	return d_1944_xhj0019(p_req1944);
        }
    }
    
    /**单笔交易查询xhj0019*/
    public RetAtsSingle d_1944_xhj0019(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        //日期格式化
        //SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String sendInfo = "{0}#{1}#{2}#{3}#@@@@";
        String tran_code = "xhj0019";//0.交易代码
        //String entryDate = df.format(new Date()) + "";//1.录入日期
        String entryDate = p_req1944.bgnDate;
        if(entryDate.length()>10){
            entryDate=entryDate.substring(0,10);
        }
        entryDate=DateHelper.convertD10toD8(entryDate);
        String FlowNo = "";//企业端流水号
        if (p_req1944.askNumber.length() <= 20) {
            FlowNo = p_req1944.askNumber;
        } else {
            retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到客户端发送的付款账号超过银行规定的最大位数20";
        }
        String PayerAcct = "";//付款账号
        if (PayerAcct.length() <= 22) {
            PayerAcct = p_req1944.payAct;
        } else {
            retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到客户端发送的付款账号超过银行规定的最大位数22";
        }
        sendInfo = MessageFormat.format(sendInfo, tran_code, entryDate, FlowNo, PayerAcct);
//	 	System.out.println("发送银行报文："+sendInfo);//打印返回报文
        try {
            String[] tmpStrRet = sendToBank(sendInfo);

            if (tmpStrRet[0].length() == 0) {
                String[] resultArr = tmpStrRet[1].split("#");
                String tmpRetCode = resultArr[0];
                if (null != tmpRetCode && !"".equals(tmpRetCode)) {
                    if (tmpRetCode.equals("000000")) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = ("1".equals(resultArr[1])) ? ("成功") : ("失败");
                        retDetail.transState = resultArr[2];
                        retDetail.payInfoCode = resultArr[2];
                        retDetail.reqSeqID = p_req1944.askNumber;
                    } else {
                        //当查询无记录时格式为 EL3016#@@@@
                        retDetail.respCode = "0";
                        retDetail.respInfo = convertRespToBank(resultArr[0]);//获取银行返回信息
                        retDetail.transState = resultArr[0];
                        retDetail.payInfoCode = resultArr[0];
                        retDetail.reqSeqID = p_req1944.askNumber;
                        if("EL3016".equals(tmpRetCode) && this.canBeNotExist(p_req1944, retDetail)){
                        	retDetail.respCode = "0";
                        }else{
                        	retDetail.respCode = "-1";
                        }
                    }
                } else {//判断如果返回的第一个节点为空则报文异常
                    retDetail.respCode = "-1";
                    retDetail.respInfo = "统一接口平台的银行接口（华夏银行）接收到银行的数据格式异常。";
                }

            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            this.WriteBankLogLn(e);
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }
    
    /**
     * 单笔转账交易结果查询（xhj5001），针对190802B，提交：xhj8016，查询：xhj5001
     * @return
     * @throws Exception
     */
    public RetAtsSingle d_1944_xhj5001(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        retDetail.respCode = "-1";
        String sendInfo = "{0}#{1}#{2}#@@@@";
        String tran_code = "xhj5001";//0.交易代码
        String entryDate = Format.Date8Format.format(p_req1944.getBgnDateTime());
        String FlowNo = p_req1944.askNumber;//企业端流水号
        
        sendInfo = MessageFormat.format(sendInfo, tran_code, entryDate, FlowNo);
        try {
            String[] tmpStrRet = sendToBank(sendInfo);

            if (tmpStrRet[0].length() == 0) {
                String[] resultArr = tmpStrRet[1].split("#");
                String tmpRetCode = resultArr[0];
                if(resultArr.length > 5){
                	retDetail.respCode = "0";
                    retDetail.transState = resultArr[0]+"+"+resultArr[1]+"+"+resultArr[2];
                    retDetail.payInfoCode = resultArr[3];
                    retDetail.respInfo = resultArr[4];
                    retDetail.reqSeqID = p_req1944.askNumber;
                }else if(resultArr.length ==2 && "@@@@".equals(resultArr[1].trim())){//当查询无记录时格式为 EL3016#@@@@
                	retDetail.respInfo = convertRespToBank(tmpRetCode);//获取银行返回信息
                	if("EL3016".equals(tmpRetCode) && this.canBeNotExist(p_req1944, retDetail)){
                		retDetail.respCode = "0";
                        retDetail.transState = tmpRetCode;
                        retDetail.payInfoCode = tmpRetCode;
                        retDetail.reqSeqID = p_req1944.askNumber;
                	}
                }else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = "银行返回的内容“"+tmpStrRet[1]+"”格式不符合预期";
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            this.WriteBankLogLn(e);
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
